package com.hrt.common.safe;

import com.btcode.common.MyLog;
import com.btcode.log.ILog;
import com.btcode.orm.model.IModel;
import com.btcode.web.core.unit.URLUtil;
import com.hrt.common.db.CommonDBManager;
import com.hrt.common.web.RequestUnit;
import java.util.List;
import javax.servlet.ServletRequest;

/**
 * 访问验证器，负责验证每个访问是否合法有权限。
 * 此类可以结合业务进行定制，比如数据库访问，配置访问等等
 */
public class VerifyService extends BaseVerifyService {

    private ILog log;

    public VerifyService() {
        log = MyLog.getInstance().getLogger(getClass());
    }

    /**
     * 该请求是否可以访问，通过验证
     */
    public boolean canAccess(ServletRequest request) {

        IUser user = UserSessionManager.getInstance().getUser();
        String requestUrl = URLUtil.getURLWithoutProjectName(request);

        if(user == null){
            log.info("无访问权限:" + requestUrl+",token:"+ RequestUnit.getString("_token"));
            return false;
        }

        if ("admin".equals(user.getAccount())) {
            return true;
        }

        List<IModel> roles = user.getRoles();

        boolean result = false;

        for (IModel role : roles) {
            role = CommonDBManager.getORMExecuter().getModel(role);
            List<IModel> functions = role.getRelationModel("C_BC_FUNCTION");

            for (IModel function : functions) {

                if (function == null) {
                    continue;
                }

                Object obj = function.getFieldValue("URL_LIST");

                if (obj == null) {
                    continue;
                }

                String[] functionUrls = obj.toString().split(",");

                for (String functionUrl : functionUrls) {
                    if (functionUrl.equals(requestUrl)) {
                        result = true;
                        break;
                    }
                    if (matchUrl(requestUrl, functionUrl)) {
                        result = true;
                        break;
                    }
                }
            }

            if(result){
                break;
            }
        }

        if (!result) {
            log.info("无访问权限:" + requestUrl);
        }
        return result;
    }

}
